let sock = null;
$(function(){
    console.log("init...");
    init();
});

function init() {
    const url = "/sockjs/text?token=1";
    sock = new SockJS(url);
    sock.onopen = function() {
        console.log("sockjs client open");
        sock.send("Hello, I am a sockjs client: " + new Date());
    };

    sock.onmessage = function(event) {
        console.log("sockjs client received message")
        console.log(event.data)
        //sock.close();

        const p = document.createElement('p');
        // 将文本中的换行符转换为HTML的<br>标签
        p.innerHTML = event.data.replace(/\n/g, '<br>');

        const container = document.getElementById('log-msg');
        // 获取容器的第一个子元素
        const firstChild = container.firstChild;
        // 若存在第一个子元素，则插入到其前面；否则直接追加
        if (firstChild) {
            container.insertBefore(p, firstChild);
        } else {
            container.appendChild(p);
        }
        container.scrollTop = 0; // 强制滚动到顶部
    };

    sock.onclose = function() {
        console.log("sockjs client closed");
    }
}